#pragma once

#include "Primitive.h"
#define _USE_MATH_DEFINES
#include <math.h>

class Cylinder: public Primitive
{
private:
	float base, top, height;
	int slices, stacks;
	GLUquadric *glQ;
public:
	Cylinder() {};
	void render()
	{
		if(getTex() != NULL)
		{
			glPushMatrix();
				drawCircle(base, 51, getTex()->getTexID());
			glPopMatrix();
			glEnable(GL_TEXTURE_2D);
				glBindTexture(GL_TEXTURE_2D, getTex()->getTexID());
				gluQuadricTexture(glQ,true);
				gluCylinder(glQ, base, top, height, slices, stacks);
			glDisable(GL_TEXTURE_2D);
			glPushMatrix();
				glTranslated(0.0,0.0,height);
				drawCircle(top, 51, getTex()->getTexID());
			glPopMatrix();
		}
		else
		{
			glPushMatrix();
				glTranslated(0.0,0.0,-height/2);
				drawCircle(base, 51, 0);
			glPopMatrix();
				gluQuadricTexture(glQ,true);
				gluCylinder(glQ, base, top, height, slices, stacks);
			glPushMatrix();
				glTranslated(0.0,0.0,height/2);
				drawCircle(top, 51, 0);
			glPopMatrix();
		}
	}
	void setQuadric(GLUquadric *g)
	{
		glQ = g;
	}
	void setValues(float b, float t, float h, int slice, int stack)
	{
		base = b;
		top = t;
		height = h;
		slices = slice;
		stacks = stack;
	}

	void drawCircle(const GLfloat radius,const GLuint num_vertex, unsigned int texSequence)
	{
		GLfloat vertex[4]; 
		GLfloat texcoord[2];
  
		const GLfloat delta_angle = 2.0*M_PI/num_vertex;
  
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D,texSequence);
		glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
		glBegin(GL_TRIANGLE_FAN);
			//desenha o vertice no centro do circulo
			texcoord[0] = 0.5;
			texcoord[1] = 0.5;
			glTexCoord2fv(texcoord);
  
			vertex[0] = vertex[1] = vertex[2] = 0.0;
			vertex[3] = 1.0;        
			glVertex4fv(vertex);
  
			for(int i = 0; i < num_vertex ; i++)
			{
				texcoord[0] = (cos(delta_angle*i) + 1.0)*0.5;
				texcoord[1] = (sin(delta_angle*i) + 1.0)*0.5;
				glTexCoord2fv(texcoord);
    
				vertex[0] = cos(delta_angle*i) * radius;
				vertex[1] = sin(delta_angle*i) * radius;
				vertex[2] = 0.0;
				vertex[3] = 1.0;
				glVertex4fv(vertex);
			}
  
			texcoord[0] = (1.0 + 1.0)*0.5;
			texcoord[1] = (0.0 + 1.0)*0.5;
			glTexCoord2fv(texcoord);
  
			vertex[0] = 1.0 * radius;
			vertex[1] = 0.0 * radius;
			vertex[2] = 0.0;
			vertex[3] = 1.0;
			glVertex4fv(vertex);
		glEnd();
  
		glDisable(GL_TEXTURE_2D);
	}
};